// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package task

import (
	"context"
	"fmt"

	"github.com/kumose/kmopt/pkg/cluster/spec"
	"github.com/kumose/kmopt/pkg/environment"
	"github.com/kumose/kmopt/pkg/repository"
)

// CopyComponent is used to copy all files related the specific version a component
// to the target directory of path
type CopyComponent struct {
	component string
	os        string
	arch      string
	version   string
	host      string
	srcPath   string
	dstDir    string
}

// Execute implements the Task interface
func (c *CopyComponent) Execute(ctx context.Context) error {
	// If the version is not specified, the last stable one will be used
	if c.version == "" {
		env := environment.GlobalEnv()
		ver, _, err := env.V1Repository().WithOptions(repository.Options{
			GOOS:   c.os,
			GOARCH: c.arch,
		}).LatestStableVersion(c.component, false)
		if err != nil {
			return err
		}
		c.version = string(ver)
	}

	// Copy to remote server
	srcPath := c.srcPath
	if srcPath == "" {
		srcPath = spec.PackagePath(c.component, c.version, c.os, c.arch)
	}

	install := &InstallPackage{
		srcPath: srcPath,
		host:    c.host,
		dstDir:  c.dstDir,
	}

	return install.Execute(ctx)
}

// Rollback implements the Task interface
func (c *CopyComponent) Rollback(ctx context.Context) error {
	return ErrUnsupportedRollback
}

// String implements the fmt.Stringer interface
func (c *CopyComponent) String() string {
	return fmt.Sprintf("CopyComponent: component=%s, version=%s, remote=%s:%s os=%s, arch=%s",
		c.component, c.version, c.host, c.dstDir, c.os, c.arch)
}
